<?php

namespace app\admin\model;

use think\Model;

/**
 * 销售单明细模型
 */
class SaleOrderItem extends Model
{
    // 表名
    protected $name = 'sale_order_item';
    
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = false;
    
    /**
     * 关联销售单
     */
    public function saleOrder()
    {
        return $this->belongsTo('SaleOrder', 'sale_order_id', 'id');
    }
    
    /**
     * 关联商品
     */
    public function product()
    {
        return $this->belongsTo('Product', 'product_id', 'id');
    }
    
    /**
     * 计算小计金额
     */
    public function getSubtotalAttr($value, $data)
    {
        return isset($data['unit_price']) && isset($data['quantity']) ? round($data['unit_price'] * $data['quantity'], 2) : 0;
    }
    
    /**
     * 计算小计进货金额
     */
    public function getPurchaseSubtotalAttr($value, $data)
    {
        return isset($data['purchase_price']) && isset($data['quantity']) ? round($data['purchase_price'] * $data['quantity'], 2) : 0;
    }
    
    /**
     * 计算总重量
     */
    public function getTotalWeightAttr($value, $data)
    {
        $jin_per_bag = isset($data['jin_per_bag']) ? floatval($data['jin_per_bag']) : 0;
        $bags_per_piece = isset($data['bags_per_piece']) ? floatval($data['bags_per_piece']) : 0;
        $quantity = isset($data['quantity']) ? intval($data['quantity']) : 0;
        
        return $jin_per_bag * $bags_per_piece * $quantity;
    }
} 